package web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录过滤器
 * 防止用户不登陆通过访问路径进行访问
 * 分别哪一些是登录资源   contains方法
 *
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2022-04-08-15:19 15:19
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //转换为HttpServletRequest
        HttpServletRequest request= (HttpServletRequest) req;
        //获取请求资源的路径
        String requestURI = request.getRequestURI();
        //是否是登录资源（这里包括，验证码，css,fonts,js,jsp等资源）
        if (requestURI.contains("/login.jsp")||requestURI.contains("/loginServlet")||requestURI.contains("/checkCode")||requestURI.contains("/css/")||requestURI.contains("/fonts/")||requestURI.contains("/js/")){
            chain.doFilter(req, resp);
        }else{
            //不是登录资源，判断是否已经登录成功
            HttpSession session = request.getSession();
            //获取session数据中的user,登录成功则有user数据
            Object user = session.getAttribute("login_user");
            if (user!=null){
                //已经登陆成功
                chain.doFilter(req, resp);
            }else{
                //未登录成功，还想访问资源
                request.setAttribute("login_error","未登录，请先登录！");
                request.getRequestDispatcher("/login.jsp").forward(req,resp);
            }

        }


    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
